<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss"
                             valueFormat="YYYY-MM-DD HH:mm:ss"/>
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss"
                             valueFormat="YYYY-MM-DD HH:mm:ss"/>
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
                <!--<a-button @click="downloadFile">下载</a-button>-->
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>

      <a-card
        :bordered="false"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="ch4Chart"
          style="height: 362px;"
          :option="methaneChartOption"/>
      </a-card>
    </div>


    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="fhdId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openSimpleDetail(record)">详情</a>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
    <DeviceFenceDataHeartbeatDataDetail v-if="showsimpleDetail" v-model:visible="showsimpleDetail" :data="current"/>
  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  TitleComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import {FenceHeartbeatDataApi} from '@/api/property/cattlehealth/FenceHeartbeatDataApi';
import DeviceFenceDataHeartbeatDataDetail from './fencedata-heartbeat-data-detail.vue';
import moment from 'moment'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  TitleComponent
]);

provide(THEME_KEY, ChartTheme);

export default {
  name: 'DeviceFenceDataHeartbeatData',
  components: {
    VChart,
    DeviceFenceDataHeartbeatDataDetail
  },
  props: {
    // 弹窗是否打开
    visible: Boolean,
    data: Object
  },
  mounted() {
    this.getNewData();
  },
  computed: {
    methaneChartOption(){
      return {
        title : {
          text : "呼吸心跳明细"
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['呼吸速率', '心跳速率', '环境温度(℃)'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            // prettier-ignore
            data: this.heartData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '呼吸速率',
            position: 'right',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#5470C6'
              }
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '心跳速率',
            position: 'right',
            alignTicks: true,
            offset: 80,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#5460C6'
              }
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '温度(℃)',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#EE6666'
              }
            },
            axisLabel: {
              formatter: '{value} °C'
            }
          }
        ],
        series: [
          {
            name: '呼吸速率',
            type: 'line',
            data: this.heartData.map(d => d.respirationRate),
            yAxisIndex: 0,
          },
          {
            name: '心跳速率',
            type: 'line',
            data: this.heartData.map(d => d.heartRate),
            yAxisIndex: 1,
          },
          {
            name: '环境温度(℃)',
            type: 'line',
            yAxisIndex: 2,
            data: this.heartData.map(d => d.envTemperature)
          }
        ]
      }
    }
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '时间',
          dataIndex: 'createTime'
        },
        {
          title: '呼吸速率(次/min)',
          dataIndex: 'respirationRate'
        },
        {
          title: '心跳速率(次/min)',
          dataIndex: 'heartRate'
        },
        {
          title: '速率状态',
          dataIndex: 'rateState',
          customRender: function (row) {
            if (row.text == 0) {
              return "无目标";
            } else if (row.text == 1) {
              return "信号微弱";
            } else if (row.text == 2) {
              return "呼吸正常";
            } else if (row.text == 3) {
              return "目标异常移动";
            }
          }
        },
        {
          title: '环境温度(℃)',
          dataIndex: 'envTemperature'
        },
        {
          title: '环境湿度',
          dataIndex: 'envHuminity'
        },
        {
          title: '热成像图',
          dataIndex: 'thermalImagingUrl',
          customRender: function (row) {
            if (row.text != undefined && row.text != '') {
              return '详情查看';
            } else {
              return '无';
            }
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {
        "fenceId": this.data.fenceId,
      },
      // 当前编辑数据
      current : null,
      // 是否显示编辑弹窗
      showDetail : false,
      heartData : [],
      showsimpleDetail : false
    }
  },
  methods: {
    getNewData() {
      let that = this;
      let params = {
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        "fenceId": that.data.fenceId,
        "orderBy": "ASC",
        "sortBy": "create_time",
        rateStates : "1,2,3"
      };

      if (this.where.searchBeginTime && this.where.searchEndTime) {
        params.searchBeginTime = this.where.searchBeginTime;
        params.searchEndTime = this.where.searchEndTime;
      }

      FenceHeartbeatDataApi.list(params).then(result => {
        let rows = result || [];
        let _heartData = [];
        if (rows && rows.length > 0) {
          rows.forEach(function (item) {
            let formatItem = {
              time: item.createTime,
              respirationRate: item.respirationRate,
              heartRate: item.heartRate,
              envTemperature : item.envTemperature
            };
            _heartData.push(formatItem);
          });
        }
        that.heartData = _heartData;
      });
    },
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({page: 1});
      this.getNewData();
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reset() {
      this.where.fenceId = this.data.fenceId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({page, limit, where, orders}) {
      return FenceHeartbeatDataApi.findPage({...where, ...orders, pageNo: page, pageSize: limit});
    },

    activated() {
      ['ch4Chart'].forEach((name) => {
        this.$refs[name].resize();
      });
    },
    openSimpleDetail(row) {
      this.current = row;
      this.showsimpleDetail = true;
    },
  }
};
</script>
